package com.example.feidaolumanager.pages

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.feidaolumanager.Constants
import com.example.feidaolumanager.MyTextField
import com.example.feidaolumanager.componant.MachineImageItem
import com.example.feidaolumanager.componant.MyBottomSelected
import com.example.feidaolumanager.pages.ui.machine.MachinesViewModel
import com.example.feidaolumanager.pages.ui.theme.FeidaoluManagerTheme
import com.example.feidaolumanager.pojo.MachineItem
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.viewModel.AreasViewModel

class MachineDetailActivity : ComponentActivity() {

    private var ifShowLargeImage: MutableState<Boolean> = mutableStateOf(false)

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 获取跳转到当前界面传的值
        val machine: MachineItem = intent.getSerializableExtra("machine") as MachineItem
        val user: User = intent.getSerializableExtra("user") as User

        val areasViewModel: AreasViewModel by viewModels()
        val machinesViewModel: MachinesViewModel by viewModels()
        areasViewModel.getAreas(user, machine)
        machinesViewModel.getMachineCategories()

        machinesViewModel.updateMachineResult.observe(this) {
            if (it != null) {
                if (it.code == Constants.success_code) {
                    Toast.makeText(this, "更新成功", Toast.LENGTH_LONG).show()
                    finish()
                } else {
                    Toast.makeText(this, "更新失败:${it.msg}", Toast.LENGTH_LONG).show()
                }
            }
        }

        setContent {
            FeidaoluManagerTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    // 机械详情界面
                    Scaffold(modifier = Modifier, topBar = {
                        TopAppBar(
                            title = {
                                if (ifShowLargeImage.value) {
                                    Text(text = "")
                                } else {
                                    Text(text = "修改设备", color = Color.White)
                                }
                            },
                            colors = TopAppBarDefaults.smallTopAppBarColors(
                                containerColor = Color(0, 172, 98)
                            ),
                            actions = {
                                if (ifShowLargeImage.value) {
                                    Icon(
                                        imageVector = Icons.Default.Close,
                                        contentDescription = "关闭全屏显示图片的按钮",
                                        modifier = Modifier
                                            .clickable {
                                                ifShowLargeImage.value = false
                                            }
                                            .size(30.dp),
                                        tint = Color.White
                                    )
                                }
                            }
                        )
                    }) { it ->

                        var largeImageUrl by remember {
                            mutableStateOf("")
                        }

                        if (ifShowLargeImage.value) {
                            Column {
                                AsyncImage(
                                    model = largeImageUrl,
                                    contentDescription = "机械图片",
                                    modifier =
                                    Modifier.fillMaxSize()
                                )
                            }

                        } else {
                            Column(
                                Modifier
                                    .padding(it)
                                    .fillMaxSize()
                                    .verticalScroll(state = rememberScrollState()),
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {

                                var labelNumber by remember {
                                    mutableStateOf(machine.locator_mobile)
                                }

                                var labelNumberErrorMsg by remember {
                                    mutableStateOf("")
                                }

                                MyTextField(
                                    label = "电子标签编号",
                                    field = labelNumber,
                                    errorMsg = labelNumberErrorMsg,
                                    onFieldChange = {
                                        labelNumber = it
                                    })

                                var ecoCode by remember {
                                    mutableStateOf(machine.mec_no)
                                }

                                var ecoCodeErrorMsg by remember {
                                    mutableStateOf("")
                                }

                                MyTextField(
                                    label = "环保编号",
                                    field = ecoCode ?: "",
                                    errorMsg = ecoCodeErrorMsg,
                                    onFieldChange = {
                                        ecoCode = it
                                    })

                                var contacts by remember {
                                    mutableStateOf(machine.contacts)
                                }

                                var contactErrorMsg by remember {
                                    mutableStateOf("")
                                }

                                MyTextField(
                                    label = "机械所有人",
                                    field = contacts ?: "",
                                    errorMsg = contactErrorMsg,
                                    onFieldChange = {
                                        contacts = it
                                    })


                                var mobile by remember {
                                    mutableStateOf(machine.mobile)
                                }

                                var mobileErrorMsg by remember {
                                    mutableStateOf("")
                                }

                                MyTextField(
                                    label = "联系方式",
                                    field = mobile ?: "",
                                    errorMsg = mobileErrorMsg,
                                    onFieldChange = {
                                        mobile = it
                                    })


                                val list1 = areasViewModel.level1AreasName
                                val list2 = areasViewModel.level2AreasName
                                val list3 = areasViewModel.level3AreasName


                                var machineType by remember {
                                    mutableStateOf(machine.type_name ?: "")
                                }


                                MyBottomSelected(
                                    context = this@MachineDetailActivity,
                                    label = "机械所在区域",
                                    list1,
                                    list2,
                                    list3,
                                    areasViewModel.updatePageMachineArea.value
                                ) { it: String, i: Int, i1: Int, i2: Int ->
                                    areasViewModel.updatePageMachineArea.value = it
                                    machine.area_one =
                                        areasViewModel.level1Areas.get(i).key.toString()
                                    machine.area_two =
                                        areasViewModel.level2Areas.get(i1).key.toString()
                                    machine.area_three =
                                        areasViewModel.level3Areas.get(i2).key.toString()
                                }

                                Spacer(modifier = Modifier.height(10.dp))

                                MyBottomSelected(
                                    context = this@MachineDetailActivity,
                                    label = "绑定机械类型",
                                    machinesViewModel.level1MachineCategoryName,
                                    machinesViewModel.level2MachineCategoryName,
                                    machinesViewModel.level3MachineCategoryName,
                                    machineType
                                ) { it: String, i: Int, i1: Int, i2: Int ->
                                    machineType = it
                                    machine.type_name = it
                                }

                                val imageHeight = 100.dp
                                // 显示所有的图片
                                LazyVerticalGrid(
                                    columns = GridCells.Fixed(2),
                                    modifier = Modifier.height(imageHeight * 2 + 50.dp)
                                ) {
                                    item {
                                        var imageAppearance by remember {
                                            mutableStateOf(machine.appearance)
                                        }
                                        MachineImageItem(
                                            activity = this@MachineDetailActivity,
                                            "外观",
                                            machineImageUrl = imageAppearance,
                                            imageHeight,
                                            0,
                                            onImageClick = {
                                                largeImageUrl = it
                                                ifShowLargeImage.value = true
                                            },
                                            onImageUploaded = {
                                                // 更新UI
                                                imageAppearance = it
                                                // 跟新数据
                                                machine.appearance = it
                                            })
                                    }
                                    item {
                                        var imageNameTag by remember {
                                            mutableStateOf(machine.name_tag)
                                        }
                                        MachineImageItem(
                                            activity = this@MachineDetailActivity,
                                            hint = "机械名牌",
                                            machineImageUrl = imageNameTag,
                                            imageHeight = imageHeight,
                                            1,
                                            onImageClick = {
                                                largeImageUrl = it
                                                ifShowLargeImage.value = true
                                            },
                                            onImageUploaded = {
                                                imageNameTag = it
                                                machine.name_tag = it
                                            }
                                        )
                                    }
                                    item {
                                        var imageEngine by remember {
                                            mutableStateOf(machine.engine)
                                        }
                                        MachineImageItem(
                                            activity = this@MachineDetailActivity,
                                            hint = "发动机铭牌",
                                            machineImageUrl = imageEngine,
                                            imageHeight = imageHeight,
                                            2,
                                            onImageClick = {
                                                largeImageUrl = it
                                                ifShowLargeImage.value = true
                                            },
                                            onImageUploaded = {
                                                imageEngine = it
                                                machine.engine = it
                                            }
                                        )
                                    }


                                    item {
                                        var imageOther by remember {
                                            mutableStateOf(machine.other ?: "")
                                        }
                                        MachineImageItem(
                                            activity = this@MachineDetailActivity,
                                            hint = "其它",
                                            machineImageUrl = imageOther,
                                            imageHeight = imageHeight,
                                            3,
                                            onImageClick = {
                                                largeImageUrl = it
                                                ifShowLargeImage.value = true
                                            },
                                            onImageUploaded = {
                                                imageOther = it
                                                machine.other = it
                                            }
                                        )
                                    }
                                }

                                Button(onClick = {
                                    labelNumberErrorMsg = if (labelNumber.isEmpty()) {
                                        "请输入电子标签编号!"
                                    } else {
                                        ""
                                    }

                                    ecoCodeErrorMsg = if (ecoCode?.isEmpty() == true) {
                                        "请输入环保编号!"
                                    } else {
                                        ""
                                    }
                                    contactErrorMsg = if (contacts?.isEmpty() == true) {
                                        "请输入所有人!"
                                    } else {
                                        ""
                                    }

                                    mobileErrorMsg = if (mobile?.isEmpty() == true) {
                                        "请输入联系电话!"
                                    } else {
                                        ""
                                    }


                                    if (labelNumberErrorMsg.isEmpty() && mobileErrorMsg.isEmpty() && contactErrorMsg.isEmpty() && ecoCodeErrorMsg.isEmpty()) {
                                        // 验证通过，提交更新
                                        machinesViewModel.updateMachine(machine)
                                    }
                                }) {
                                    Text(text = "更新")
                                }
                            }
                        }


                    }
                }
            }
        }
    }


    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (ifShowLargeImage.value) {
            ifShowLargeImage.value = false

        } else {
            super.onBackPressed()
        }
    }
}

